﻿using System;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Data;
using System.Web.Caching;
using System.Configuration;
using System.Net;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace teacher.Util
{
    public class Helper
    {
        public static string webservicePath = ConfigurationManager.AppSettings["webservicePath"];

        //默认密钥向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /// <summary>
        /// 默认密钥
        /// </summary>
        private static string miyue = "88888888";

        /// <summary>
        /// 加密文本
        /// </summary>
        /// <param name="txt">需要加密的文本</param>
        /// <returns></returns>
        public static string DESencrypt(string txt)
        {
            string chuliTxt = string.Empty;
            try
            {
                //string encryptKey加密密钥参数，我将该参数这里去掉了，用了默认密钥
                //byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbKey = Encoding.UTF8.GetBytes(miyue);//加密密钥 
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(txt);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                byte[] tembyte = mStream.ToArray();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < tembyte.Length; i++)
                {
                    sb.AppendFormat("{0:x2}", tembyte[i]);
                }
                chuliTxt = sb.ToString();
            }
            catch (Exception)
            {
                throw;
            }
            return chuliTxt;
        }

        /// <summary>
        /// 解密文本
        /// </summary>
        /// <param name="txt">需要解密的文本</param>
        /// <returns></returns>
        public static string DESDecoding(string txt)
        {
            string chuliTxt = string.Empty;
            try
            {
                //string decryptKey解密密钥参数，我将该参数这里去掉了，用了默认密钥
                //byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbKey = Encoding.UTF8.GetBytes(miyue);//解密密钥 
                byte[] rgbIV = Keys;
                txt = txt.Replace(" ", "");
                txt = txt.Replace("\r\n", "");
                string txt16 = txt;
                byte[] inputByteArray = new byte[txt16.Length / 2];
                for (int i = 0; i < inputByteArray.Length; i++)
                {
                    inputByteArray[i] = Convert.ToByte(txt16.Substring(i * 2, 2), 16);
                }
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                chuliTxt = Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception)
            {
                throw;
            }
            return chuliTxt;
        }

        public static string sendOKJson(HttpRequestBase Request, object obj)
        {
            string callbackName = (string)Request["jsoncallback"];
            string jsonStr = "[]";
            if (obj != null)
            {
                jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            }
            if (!string.IsNullOrEmpty(callbackName))
            {
                return callbackName + "({\"code\":\"1\",\"data\":" + jsonStr + "})";
            }
            else
            {
                return "{\"code\":\"1\",\"data\":" + jsonStr + "}";
            }
        }

        public static string sendErrorJson(HttpRequestBase Request, string msg)
        {
            string callbackName = (string)Request["jsoncallback"];
            if (!string.IsNullOrEmpty(callbackName))
            {
                return callbackName + "({\"code\":\"0\",\"msg\":\"" + msg + "\"})";
            }
            else
            {
                return "{\"code\":\"0\",\"msg\":\"" + msg + "\"}";
            }
        }

        public static DataTable getToken(HttpRequestBase Request)
        {
            if (System.Web.HttpRuntime.Cache[Request["token"]] == null)
            {
                DataTable dt = DbHelper.ExecuteDataTable(string.Format("select * from t_token where token='{0}'", Request["token"]));
                if (dt.Rows.Count > 0)
                {
                    DataTable tearcher = DbHelper.ExecuteDataTable(string.Format("select * from t_teacher where id='{0}'", dt.Rows[0]["t_id"]));
                    System.Web.HttpRuntime.Cache.Add(Request["token"], tearcher, null, DateTime.Now.AddDays(1), TimeSpan.Zero, CacheItemPriority.Normal, null);
                    return tearcher;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                DataTable dt = (DataTable)System.Web.HttpRuntime.Cache[Request["token"]];
                return dt;
            }
        }

        // <summary>  
        /// 无损压缩图片  
        /// </summary>  
        /// <param name="sFile">原图片</param>  
        /// <param name="dFile">压缩后保存位置</param>  
        /// <param name="dHeight">高度</param>  
        /// <param name="dWidth">宽度</param>  
        /// <param name="flag">压缩质量 1-100</param>  
        /// <returns></returns>  
        public static bool CompressImage(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {

            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放  
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时，设置压缩质量  
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100  
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径  
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }

        }

        /// <summary>
        /// 按照指定大小缩放图片，但是为了保证图片宽高比自动截取
        /// </summary>
        /// <param name="srcImage"></param>
        /// <param name="iWidth"></param>
        /// <param name="iHeight"></param>
        /// <returns></returns>
        public static void SizeImageWithOldPercent(string sFile, string dFile, int iWidth, int iHeight)
        {
            try
            {
                System.Drawing.Image srcImage = System.Drawing.Image.FromFile(sFile);
                // 要截取图片的宽度（临时图片）
                int newW = srcImage.Width;
                // 要截取图片的高度（临时图片）
                int newH = srcImage.Height;
                // 截取开始横坐标（临时图片）
                int newX = 0;
                // 截取开始纵坐标（临时图片）
                int newY = 0;
                // 截取比例（临时图片）
                double whPercent = 1;
                whPercent = ((double)iWidth / (double)iHeight) * ((double)srcImage.Height / (double)srcImage.Width);
                if (whPercent > 1)
                {
                    // 当前图片宽度对于要截取比例过大时
                    newW = int.Parse(Math.Round(srcImage.Width / whPercent).ToString());
                }
                else if (whPercent < 1)
                {
                    // 当前图片高度对于要截取比例过大时
                    newH = int.Parse(Math.Round(srcImage.Height * whPercent).ToString());
                }
                if (newW != srcImage.Width)
                {
                    // 宽度有变化时，调整开始截取的横坐标
                    newX = Math.Abs(int.Parse(Math.Round(((double)srcImage.Width - newW) / 2).ToString()));
                }
                else if (newH == srcImage.Height)
                {
                    // 高度有变化时，调整开始截取的纵坐标
                    newY = Math.Abs(int.Parse(Math.Round(((double)srcImage.Height - (double)newH) / 2).ToString()));
                }
                // 取得符合比例的临时文件
                Bitmap cutedImage = CutImage(srcImage, newX, newY, newW, newH);
                // 保存到的文件
                Bitmap b = new Bitmap(iWidth, iHeight);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.Default;
                g.DrawImage(cutedImage, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, cutedImage.Width, cutedImage.Height), GraphicsUnit.Pixel);
                g.Dispose();
                b.Save(dFile);
                b.Dispose();
                srcImage.Dispose();
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 剪裁 -- 用GDI+
        /// </summary>
        /// <param name="b">原始Bitmap</param>
        /// <param name="StartX">开始坐标X</param>
        /// <param name="StartY">开始坐标Y</param>
        /// <param name="iWidth">宽度</param>
        /// <param name="iHeight">高度</param>
        /// <returns>剪裁后的Bitmap</returns>
        public static Bitmap CutImage(Image b, int StartX, int StartY, int iWidth, int iHeight)
        {
            if (b == null)
            {
                return null;
            }
            int w = b.Width;
            int h = b.Height;
            if (StartX >= w || StartY >= h)
            {
                // 开始截取坐标过大时，结束处理
                return null;
            }
            if (StartX + iWidth > w)
            {
                // 宽度过大时只截取到最大大小
                iWidth = w - StartX;
            }
            if (StartY + iHeight > h)
            {
                // 高度过大时只截取到最大大小
                iHeight = h - StartY;
            }
            try
            {
                Bitmap bmpOut = new Bitmap(iWidth, iHeight);
                Graphics g = Graphics.FromImage(bmpOut);
                g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
                g.Dispose();
                return bmpOut;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 按照指定大小缩放图片
        /// </summary>
        /// <param name="srcImage"></param>
        /// <param name="iWidth"></param>
        /// <param name="iHeight"></param>
        /// <returns></returns>
        public static bool SizeImage(string sFile, string dFile, int iWidth, int iHeight)
        {
            try
            {
                System.Drawing.Image srcImage = System.Drawing.Image.FromFile(sFile);
                // 要保存到的图片
                Bitmap b = new Bitmap(iWidth, iHeight);
                Graphics g = Graphics.FromImage(b);
                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(srcImage, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
                g.Dispose();
                b.Save(dFile);
                b.Dispose();
                srcImage.Dispose();
                return true;
            }
            catch (Exception)
            {
                return false;

            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file1"></param>
        /// <param name="allowExtension"></param>
        /// <param name="path"></param>
        /// <param name="size"></param>
        /// <returns></returns>

        public static string Upload(HttpPostedFileBase file1, string[] allowExtension, string path, int size)
        {
            string result = "";
            try
            {

                //取得文件的扩展名,并转换成小写
                string fileExtension = System.IO.Path.GetExtension(file1.FileName).ToLower();
                //对上传的文件的类型进行一个个匹对
                //验证文件格式
                if (allowExtension.Contains(fileExtension))
                {
                    if (file1.ContentLength < 1024 * 1024 * 2)
                    {
                        file1.SaveAs(Path.Combine(path));
                        result = "1";
                    }
                    else
                    {
                        result = "40010";
                    }
                }
                else
                {
                    result = "40009";
                }
            }
            catch
            {
                result = "0";
            }
            return result;
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="content"></param>
        public static void WriteLog(string content)
        {
            string path = "D:\\log\\";
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            path += DateTime.Now.ToString("yyyyMMdd") + ".txt";
            if (!File.Exists(path))
            {
                FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件
                /**/
                ///根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs1);

                /**/
                ///设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);

                /**/
                ///写入“Log Entry : ”
                w.Write("\nLog Entry : ");

                /**/
                ///写入当前系统时间并换行
                w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
                   DateTime.Now.ToLongDateString());

                /**/
                ///写入日志内容并换行
                w.Write(content + "\n");

                /**/
                ///写入------------------------------------“并换行
                w.Write("------------------------------------\n");

                /**/
                ///清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();

                fs1.Close();
            }
            else
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);

                StreamWriter sr = new StreamWriter(fs);
                /**/
                ///根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);

                /**/
                ///设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);

                /**/
                ///写入“Log Entry : ”
                w.Write("\nLog Entry : ");

                /**/
                ///写入当前系统时间并换行
                w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
                   DateTime.Now.ToLongDateString());

                /**/
                ///写入日志内容并换行
                w.Write(content + "\n");

                /**/
                ///写入------------------------------------“并换行
                w.Write("------------------------------------\n");

                /**/
                ///清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();
                sr.Close();
                fs.Close();
            }
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="codeName">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string EncodeBase64(Encoding encode, string source)
        {
            byte[] bytes = encode.GetBytes(source);
            try
            {
                return Convert.ToBase64String(bytes);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public static string EncodeBase64(string source)
        {
            return EncodeBase64(Encoding.UTF8, source);
        }
        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string getWebServiceJson(string url)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "GET";
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            return content;
        }

        public static string stripHtml(string strhtml)
        {
            string stroutput = strhtml;
            Regex regex = new Regex(@"<[^>]+>|</[^>]+>");
            stroutput = regex.Replace(stroutput, "").Replace("&nbsp;", "");
            return stroutput;
        }
        public static bool isInt(string txt)
        {
            try
            {
                Convert.ToInt32(txt);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 模块枚举
        /// </summary>
        public enum ModelsEnum
        {
            校园新闻 = 1,
            通知活动 = 2,
            宝贝课程 = 3,
            签到代接 = 4,
            宝宝食谱 = 5,
            宝宝视频 = 6,
            校园简介 = 7,
            互动留言 = 8,
            成长档案 = 9
        }
    }
}